package com.steerinfo.dil.config;

import com.alibaba.fastjson.JSON;
import com.steerinfo.dil.annotaion.RequestLimit;
import com.steerinfo.framework.cache.server.redis.RedisCache;
import com.steerinfo.framework.controller.RESTfulResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class RepeatRequestIntercept extends HandlerInterceptorAdapter {
    @Autowired
    private RedisCache redisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求是否为方法的请求
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法中是否有幂等性注解
            RequestLimit anno = hm.getMethodAnnotation(RequestLimit.class);
            //若注解为空则直接返回
            if (Objects.isNull(anno)) {
                return true;
            }
            int seconds = anno.seconds();
            int max = anno.maxCount();
            String key = request.getRemoteAddr() + "-" + request.getMethod() + "-" + request.getRequestURL();
            Object requestCountObj = redisUtils.get(key);
            if (Objects.isNull(requestCountObj)) {
                //若为空则为第一次请求
                redisUtils.setex(key, 1,"ok");
            } else {
                //限定时间内的第n次请求
                int requestCount = Integer.parseInt(requestCountObj.toString());
                //判断是否超过最大限定请求次数
                if (requestCount < max) {
                    //未超过则请求次数+1
                    redisUtils.incr(key, 1);
                } else {
                    //否则拒绝请求并返回信息
                    refuse(response);
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * @param response
     * @date 2023-08-10 15:25
     * @author Bummon
     * @description 拒绝请求并返回结果
     */
    private void refuse(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream os = response.getOutputStream();
        RESTfulResult result = new RESTfulResult();
        result.setFailed();
        result.setMessage("请求已提交，请勿重复请求");
        result.setCode("100");
        String jsonString = JSON.toJSONString(result);
        os.write(jsonString.getBytes());
        os.flush();
        os.close();
    }
}
